package com.ocom.webapi.controller;

import com.alibaba.fastjson.JSON;
import com.ocom.common.constant.WebApiServiceUrl;
import com.ocom.common.entity.company.EntityCompanyInfo;
import com.ocom.common.entity.master.EntityWechatAppInfo;
import com.ocom.common.entity.pay.EntityAppConfig;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.company.GetGzhListOfComRequest;
import com.ocom.common.request.web.WebAppConfigGetFuncVo;
import com.ocom.common.request.web.WebAppConfigSetGzhMenuVo;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.CommonUtil;
import com.ocom.common.utils.HttpRequest;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.vo.company.GzhCodeOfComVo;
import com.ocom.common.vo.webapi.*;
import com.ocom.webapi.feign.CompanyClientService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: TODO
 * @Author: 朱晖
 * @Date: 2022/11/25
 **/
@Slf4j
@RestController
@PreAuthorize("@pms.hasRole('ROLE_WEB')" )
public class AppConfigController {

	@Autowired
	CompanyClientService companyClientService;

	@PostMapping(WebApiServiceUrl.URL_AppConfigGetFunc)
	public Result GetFunc(@RequestBody WebAppConfigGetFuncVo webAppConfigGetFuncVo) {
		return companyClientService.getAppFunc(webAppConfigGetFuncVo);
	}

	@PostMapping(WebApiServiceUrl.URL_AppConfigSetFunc)
	public Result SetFunc(@RequestBody EntityAppConfig entityAppConfig) {
		return companyClientService.setAppFunc(entityAppConfig);
	}

	@PostMapping(WebApiServiceUrl.URL_AppConfigGetGzhList)
	public Result GetGzhList(@RequestBody ComIdVo comIdVo) {
		Map<String, Object> map = new HashMap<>();
		map.put("comId", comIdVo.getComId());
		Result result = companyClientService.GetCompanyInfo(map);
		if (result.getCode() != 200) {
			return ResultUtil.error(ResultEnum.Err_301);
		}
		EntityCompanyInfo entityCompanyInfo = JSON.parseObject(JSON.toJSONString(result.getData()), EntityCompanyInfo.class);


		Result result11 = companyClientService.getGzhCodeOfCom(comIdVo.getComId());
		GzhCodeOfComVo gzhCodeOfComVo = JSON.parseObject(JSON.toJSONString(result11.getData()), GzhCodeOfComVo.class);



		List<GzhListVo> gzhListVos = new ArrayList<>();

		Map<String, Object> resMap = new HashMap<>();
		resMap.put("comId", comIdVo.getComId());
		resMap.put("comIdCode", gzhCodeOfComVo.getComIdCode());
		resMap.put("gzhList", new ArrayList<>());

		//代理商
		if (entityCompanyInfo.getIsAgent() == 1) {
			resMap.put("agentId", 1);

			GetGzhListOfComRequest request = new GetGzhListOfComRequest();
			request.setComId(comIdVo.getComId());
			request.setIsAgent(-10);
			Result result1 = companyClientService.getGzhListOfCom(request);

			if (result1.getCode() != 200) {
				return ResultUtil.success(resMap);
			}

			List<EntityWechatAppInfo> list = JSON.parseArray(JSON.toJSONString(result1.getData()), EntityWechatAppInfo.class);
			for (EntityWechatAppInfo entityWechatAppInfo : list) {
				GzhListVo gzhListVo = new GzhListVo();
				gzhListVo.setAppid(entityWechatAppInfo.getAppid());
				gzhListVo.setAppName(entityWechatAppInfo.getAppName());
				gzhListVo.setRemark(entityWechatAppInfo.getRemark());
				gzhListVo.setMyApp(true);
				gzhListVos.add(gzhListVo);
			}

		} else {
			//单位展示代理商
			GetGzhListOfComRequest request = new GetGzhListOfComRequest();
			request.setComId(entityCompanyInfo.getAgentId());
			request.setIsAgent(-10);
			Result result1 = companyClientService.getGzhListOfCom(request);

			//单位
			resMap.put("agentId", 0);
			if (result1.getCode() == 200) {
				List<EntityWechatAppInfo> list = JSON.parseArray(JSON.toJSONString(result1.getData()), EntityWechatAppInfo.class);
				for (EntityWechatAppInfo entityWechatAppInfo : list) {
					GzhListVo gzhListVo = new GzhListVo();
					gzhListVo.setAppid(entityWechatAppInfo.getAppid());
					gzhListVo.setAppName(entityWechatAppInfo.getAppName());
					gzhListVo.setRemark(entityWechatAppInfo.getRemark());
					gzhListVo.setMyApp(false);
					gzhListVos.add(gzhListVo);
				}
			}

			GetGzhListOfComRequest request2 = new GetGzhListOfComRequest();
			request2.setComId(comIdVo.getComId());
			request2.setIsAgent(-1);
			Result result2 = companyClientService.getGzhListOfCom(request2);
			if (result2.getCode() == 200) {
				List<EntityWechatAppInfo> list2 = JSON.parseArray(JSON.toJSONString(result2.getData()), EntityWechatAppInfo.class);
				for (EntityWechatAppInfo entityWechatAppInfo : list2) {
					GzhListVo gzhListVo = new GzhListVo();
					gzhListVo.setAppid(entityWechatAppInfo.getAppid());
					gzhListVo.setAppName(entityWechatAppInfo.getAppName());
					gzhListVo.setRemark(entityWechatAppInfo.getRemark());
					gzhListVo.setMyApp(true);
					gzhListVos.add(gzhListVo);
				}
			}
		}

		resMap.put("gzhList", gzhListVos);

		return ResultUtil.success(resMap);
	}

	@PostMapping(WebApiServiceUrl.URL_AppConfigSetGzhInfo)
	public Result SetGzhInfo(@RequestBody EntityWechatAppInfo entityWechatAppInfo) {
		return companyClientService.setAppInfo(entityWechatAppInfo);
	}

	@PostMapping(WebApiServiceUrl.URL_AppConfigSetGzhMenu)
	public Result SetGzhMenu(@RequestBody WebAppConfigSetGzhMenuVo webAppConfigVo) {
		Result result = companyClientService.getAppInfo(webAppConfigVo.getComId(), webAppConfigVo.getAppid());
		if (result.getCode() != 200) {
			return result;
		}
		EntityWechatAppInfo entityWechatAppInfo = JSON.parseObject(JSON.toJSONString(result.getData()), EntityWechatAppInfo.class);

		Result result23 = companyClientService.getGzhCodeOfCom(entityWechatAppInfo.getComId());
		GzhCodeOfComVo gzhCodeOfComVo = JSON.parseObject(JSON.toJSONString(result23.getData()), GzhCodeOfComVo.class);

		//token
		String gzhUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + entityWechatAppInfo.getAppid() + "&secret=" + entityWechatAppInfo.getAppsecret();

		//{"access_token":"ACCESS_TOKEN","expires_in":7200}
//{"access_token":"63_yfME3Q7VI6MD99w-rch0JqHuv7Z2EhF4ZZy7z6tY39sAkINmkP-Ua4PBwkCjIkERxS1zhvGzUMEFgFX7proXg6M3AHo9PuB1l39DWsRziSITFgPDYKlph1Lu944BBWfAAAIID","expires_in":7200}

		String opp = HttpRequest.sendGet(gzhUrl);

		log.info("获取Gzh-token 【{}】", opp);

		Map<String, Object> res = JSON.parseObject(opp, Map.class);

		if (res.containsKey("access_token")) {
			String token = (String) res.get("access_token");

			String setUrl = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + token;

			WebAppConfigGetFuncVo webAppConfigGetFuncVo = new WebAppConfigGetFuncVo();
			webAppConfigGetFuncVo.setComId(entityWechatAppInfo.getComId());
			webAppConfigGetFuncVo.setAppid(entityWechatAppInfo.getAppid());
			Result result2 = companyClientService.getAppFunc(webAppConfigGetFuncVo);


			EntityAppConfig entityAppConfig = null;
			if (result2.getCode() == 200) {
				entityAppConfig = JSON.parseObject(JSON.toJSONString(result2.getData()), EntityAppConfig.class);
			}
			String registerUrl = null;
			String bindUrl = null;
			String loginUrl = null;

			/**
			 * 4、调用单位微服务接口3.16 urlBindRegister（参数：bind、register）获取pageUrl
			 * 如果pageUrl为空，bindUrl :=空
			 * 否则bindUrl := pageUrl + “?AppName=” + app_name + “&com_id_code=” + comIdCode
			 */
			if (entityAppConfig != null && entityAppConfig.getRegister()>0) {
				if (entityWechatAppInfo.getMerchId() != -1) {
					registerUrl = "http://gzh.ocom30.com/companyList" +
							"?appName=" + entityWechatAppInfo.getAppName() +
							"&bindRegister=2";
				} else {
					Result result3 = companyClientService.urlBindRegister(entityAppConfig.getBind(), 0);
					if (result3.getCode() == 200) {
						Map<String, String> map1 = JSON.parseObject(JSON.toJSONString(result3.getData()), Map.class);
						//bindUrl := pageUrl + “?AppName=” + app_name + “&com_id_code=” + comIdCode
						registerUrl = map1.get("pageUrl") +
								"?appName=" + entityWechatAppInfo.getAppName() +
								"&comIdCode=" + gzhCodeOfComVo.getComIdCode();
					}
				}
			}
			if (entityAppConfig != null && entityAppConfig.getBind()>0) {
				if (entityWechatAppInfo.getMerchId() != -1) {
					bindUrl = "http://gzh.ocom30.com/companyList" +
							"?appName=" + entityWechatAppInfo.getAppName() +
							"&bindRegister=1";
				} else {
					Result result3 = companyClientService.urlBindRegister(0, entityAppConfig.getRegister());
					if (result3.getCode() == 200) {
						Map<String, String> map = JSON.parseObject(JSON.toJSONString(result3.getData()), Map.class);
						//bindUrl := pageUrl + “?AppName=” + app_name + “&com_id_code=” + comIdCode
						bindUrl = map.get("pageUrl") +
								"?appName=" + entityWechatAppInfo.getAppName() +
								"&comIdCode=" + gzhCodeOfComVo.getComIdCode();
					}
				}
			}

			List<GzhSetInt2Vo> gzhSetIntVos = new ArrayList<>();

			GzhSetInt2Vo gzhSetIntVo = new GzhSetInt2Vo();
			gzhSetIntVo.setType("click");
			gzhSetIntVo.setName("用户中心");

			if (!CommonUtil.isNull(registerUrl)) {
				GzhSetInt2Vo gzhSetIntVo1 = new GzhSetInt2Vo();
				gzhSetIntVo1.setName("注册");
				gzhSetIntVo1.setUrl(registerUrl);
				gzhSetIntVo.getSub_button().add(gzhSetIntVo1);
			}

			if (!CommonUtil.isNull(bindUrl)) {
				GzhSetInt2Vo gzhSetIntVo2 = new GzhSetInt2Vo();
				gzhSetIntVo2.setName("绑定");
				gzhSetIntVo2.setUrl(bindUrl);
				gzhSetIntVo.getSub_button().add(gzhSetIntVo2);
			}

			GzhSetInt2Vo gzhSetIntVo3 = new GzhSetInt2Vo();
			gzhSetIntVo3.setName("云卡通");
			if (entityWechatAppInfo.getMerchId() == -1) {
				gzhSetIntVo3.setName("校园卡");
			}
			gzhSetIntVo3.setUrl("http://gzh.ocom30.com/home?appName=" + entityWechatAppInfo.getAppName() + "&comIdCode=" + gzhCodeOfComVo.getComIdCode());

			gzhSetIntVo.getSub_button().add(gzhSetIntVo3);

			gzhSetIntVos.add(gzhSetIntVo);

			GzhSetVo gzhSetVo = new GzhSetVo();
			gzhSetVo.setName("cescece");
			gzhSetVo.setSub_button(gzhSetIntVos);

			Map<String, Object> map = new HashMap<>();
			map.put("button", gzhSetIntVos);

			log.info("JSON 【{}】", JSON.toJSONString(map));

			String res1 = HttpRequest.sendPost(setUrl, JSON.toJSONString(map));

			//{"errcode":0,"errmsg":"ok"}】

			log.info("公众号配置菜单 参数 【{}】返回 【{}】", webAppConfigVo, res1);

			return ResultUtil.success();
		}

		/**
		 * {
		 *     "button": [
		 *         {
		 *             "name": "扫码",
		 *             "sub_button": [
		 *                 {
		 *                     "type": "scancode_push",
		 *                     "name": "扫码推事件",
		 *                     "key": "rselfmenu_0_1",
		 *                     "sub_button": [
		 *                       {
		 *                       "type": "view",
		 *                       "name": "搜索",
		 *                       "url": "http://www.soso.com/"
		 *                       }, {
		 *                        "type": "view",
		 *                       "name": "搜索",
		 *                        "url": "http://www.soso.com/"
		 *                      },
		 * 		 			]
		 *                 }
		 *             ]
		 *         }
		 *     ]
		 * }
		 */

		return ResultUtil.error(ResultEnum.Err_3014);
	}

}
